import { useEffect } from 'react'
import { useState } from 'react'

import { getCitiesTreeApi } from '@/api/pcs/cities'
import {
  createCompanionComboApi,
  getCompanionComboDetailApi,
  updateCompanionComboApi,
} from '@/api/pcs/pcsCompanionCombo'
import { companionFlowListApi } from '@/api/pcs/pcsCompanionFlow'
import { hospitalListApi } from '@/api/pcs/pcsHospital'
import AekDrawer, { PromiseThen } from '@/components/AekDrawer'
import AekForm from '@/components/AekForm'
import {
  BOOLEAN_ENUM,
  HAVE_ENUM,
  PCS_COMBO_TYPE_ENUM,
  PCS_COMPANION_CHARGE_MODEL_ENUM,
  PCS_COMPANION_SELECTION_ENUM,
  PCS_COMPANION_WAY_ENUM,
  PCS_DAYS_ETTLEMENT_CHARGE_MODEL_ENUM,
  PCS_END_DATE_CHARGE_MODEL_ENUM,
  PCS_OUTSOURCING_SETTLE_TYPE_ENUM,
  PCS_START_DATE_CHARGE_MODEL_ENUM,
} from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

const EditDrawer = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const quickEntrance = AekForm.useWatch('quickEntrance', form)
  const homeServer = AekForm.useWatch('homeServer', form)
  const hospitalServer = AekForm.useWatch('hospitalServer', form)
  const incentive = AekForm.useWatch('incentive', form)
  const outsourcingSettleType = AekForm.useWatch('outsourcingSettleType', form)
  const { id } = row

  const [loading, setLoading] = useState(false)

  const getDetail = async () => {
    setLoading(true)
    const { data } = await requestWithTry(getCompanionComboDetailApi, {
      id,
    }).finally(() => setLoading(false))
    form.setFieldsValue({
      ...data,
      companionFlowId: String(data.companionFlowId),
      hospitalAreaIdList: data?.hospitalAreaIdList?.map(String),
      homeAreaIdList: data?.homeAreaIdList?.map(Number),
    })
  }

  useEffect(() => {
    form.setFieldsValue({
      companionSelection: PCS_COMPANION_SELECTION_ENUM.NON_EXCLUSIVE,
      comboType: PCS_COMBO_TYPE_ENUM.ACCOMPANYING,
      quickEntrance: BOOLEAN_ENUM.FALSE,
      homeServer: BOOLEAN_ENUM.FALSE,
      hospitalServer: BOOLEAN_ENUM.FALSE,
      incentive: HAVE_ENUM.NOT_HAVE,
      outsourcingSettleType: PCS_OUTSOURCING_SETTLE_TYPE_ENUM.PERCENT,
    })
    if (!id) return
    getDetail()
  }, [id])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'name',
      label: '套餐名称',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input', props: { maxLength: 20, placeholder: '请输入，限20字' } },
    },
    {
      field: 'companionSelection',
      label: '陪护选择',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'RadioGroup', props: { options: PCS_COMPANION_SELECTION_ENUM.options } },
    },
    {
      field: 'comboType',
      label: '套餐类型',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: PCS_COMBO_TYPE_ENUM.options,
        },
      },
    },
    {
      field: 'content',
      label: '套餐内容',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'AekTextArea', props: { maxLength: 200 } },
    },
    {
      field: 'comboMainImg',
      label: '套餐主图',
      formItemProps: {
        rules: [{ required: true }],
        help: '限上传一张 800*800 的图片，限jpg、png格式',
      },
      component: {
        name: 'AekUpload',
        props: { fileType: 'img', listType: 'picture-card', limitFileNum: 1, accept: '.jpg,.png' },
      },
    },
    {
      field: 'comboDetailImgList',
      label: '套餐详情图',
      formItemProps: {
        help: '限jpg、png格式，最多上传 10 张',
      },
      component: {
        name: 'AekUpload',
        props: { fileType: 'img', listType: 'picture-card', limitFileNum: 10, accept: '.jpg,.png' },
      },
    },
    {
      field: 'quickEntrance',
      label: '快捷入口',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'RadioGroup', props: { options: BOOLEAN_ENUM.options } },
    },
    {
      exclude: !quickEntrance,
      field: 'entranceWeight',
      label: '入口权重',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekInputNumber',
        props: {
          min: 0,
          max: 1000,
          precision: 0,
          controls: true,
          placeholder: '请输入入口权重，最小0，最大1000',
        },
      },
    },
    {
      exclude: !quickEntrance,
      field: 'entranceImg',
      label: '入口图标',
      formItemProps: {
        rules: [{ required: true }],
        help: '限上传一张，限png格式',
      },
      component: {
        name: 'AekUpload',
        props: { fileType: 'img', listType: 'picture-card', limitFileNum: 1, accept: '.png' },
      },
    },
    {
      field: 'companionWay',
      label: '陪护方式',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: PCS_COMPANION_WAY_ENUM.options,
        },
      },
    },
    {
      field: 'companionFlowId',
      label: '陪护流程',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          api: companionFlowListApi,
        },
      },
    },
    {
      field: 'homeServer',
      label: '居家服务',
      component: { name: 'RadioGroup', props: { options: BOOLEAN_ENUM.options } },
    },
    {
      exclude: !homeServer,
      field: 'homeAreaIdList',
      label: '区域范围',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekTreeSelect',
        props: {
          api: getCitiesTreeApi,
          treeCheckable: true,
          // multiple: true,
        },
      },
    },
    {
      field: 'hospitalServer',
      label: '住院服务',
      component: { name: 'RadioGroup', props: { options: BOOLEAN_ENUM.options } },
    },
    {
      exclude: !hospitalServer,
      field: 'hospitalAreaIdList',
      label: '医院范围',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          api: hospitalListApi,
          mode: 'multiple',
        },
      },
    },
    {
      field: 'chargeModel',
      label: '计费方式',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: PCS_COMPANION_CHARGE_MODEL_ENUM.options,
        },
      },
    },
    // TODO：跨天结算
    {
      label: '跨天结算',
      view: true,
      viewRender: () => '',
    },
    {
      field: 'startDateChargeModel',
      label: '开始日',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: PCS_START_DATE_CHARGE_MODEL_ENUM.getOptions([PCS_START_DATE_CHARGE_MODEL_ENUM.ONE_DAY]),
        },
      },
    },
    {
      field: 'endDateChargeModel',
      label: '结束日',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: PCS_END_DATE_CHARGE_MODEL_ENUM.getOptions([PCS_END_DATE_CHARGE_MODEL_ENUM.HALF_A_DAY_BEFORE_12]),
        },
      },
    },
    {
      field: 'daySettlementChargeModel',
      label: '当日结算',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: PCS_DAYS_ETTLEMENT_CHARGE_MODEL_ENUM.getOptions([PCS_DAYS_ETTLEMENT_CHARGE_MODEL_ENUM.ONE_DAY]),
        },
      },
    },
    {
      field: 'price',
      label: '价格',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: /^[0-9]*$/i,
            message: '请输入整数',
          },
        ],
      },
      component: {
        name: 'AekInputNumber',
        props: {
          min: 0,
          step: 1,
        },
      },
      other: '/ 天',
    },
    {
      field: 'incentive',
      label: '激励政策',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'RadioGroup',
        props: {
          options: HAVE_ENUM.options,
        },
      },
    },
    {
      exclude: !incentive,
      field: 'incentivePercent',
      label: '激励方式',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'InputNumber',
        props: {
          className: 'w-full',
          placeholder: '提成百分比',
          min: 0,
          max: 100,
          step: 0.01,
          precision: 2,
        },
      },
      other: '%',
    },
    {
      label: '外包结算',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: [
        {
          field: 'outsourcingSettleType',
          component: {
            name: 'Select',
            props: {
              width: '100px',
              options: PCS_OUTSOURCING_SETTLE_TYPE_ENUM.options,
              allowClear: false,
            },
          },
          formItemProps: {
            rules: [{ required: true }],
          },
        },
        {
          field: 'outsourcingSettleValue',
          component: {
            name: 'AekInputNumber',
            props: {
              min: 0,
              step: 1,
            },
          },
          formItemProps: {
            rules: [{ required: true }],
          },
        },
      ],
      other: outsourcingSettleType === PCS_OUTSOURCING_SETTLE_TYPE_ENUM.PERCENT ? '%' : '元 / 天',
    },
    {
      field: 'remark',
      label: '备注',
      component: { name: 'AekTextArea', props: { placeholder: '请输入' } },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      id,
      entranceWeight: 0, // 即使快捷入口选否，也必须传值，否则会报错
      ...values,
      comboMainImg: values.comboMainImg?.map(item => item.url).join(','),
      comboDetailImgList: values.comboDetailImgList?.map(item => item.url),
      entranceImg: values.entranceImg?.map(item => item.url).join(','),
    }
    await requestWithTry(id ? updateCompanionComboApi : createCompanionComboApi, params)
  }

  return (
    <AekDrawer title={id ? '编辑' : '新增'} width={500} onOk={onOk} loading={loading}>
      <AekForm form={form} formData={formData} />
    </AekDrawer>
  )
}

EditDrawer.PromiseThen = PromiseThen

export default EditDrawer
